import React, { Component } from 'react';
import { promptBox, cacheTools, base, toast } from 'nc-lightapp-front';
import { hrAjax as ajax, saveValidate} from 'src/hrpub/common/utils/utils';
import { chectFormAction } from 'src/hrcm/public/functions/checkFormAction';
import './index.less';

const { NCModal, NCButton } = base;
class MainCard extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showAgreement: false,
			effectParam: null,
			justFrom: null,
			stepData: null
		};
		this.terminateAgreement = this.terminateAgreement.bind(this);
		this.done = this.done.bind(this);
		this.setShowAgreement = this.setShowAgreement.bind(this);
	}
	setShowAgreement(data, params) {
		const { table, areaCode, meta } = this.props;
		this.setState({ showAgreement: true, effectParam: params }, () => {
			// this.openAgreementModal();
			let allMetas = meta.getMeta();
			let tempid = areaCode.agreement;
			if (`${areaCode.agreement}_add` in allMetas) {
				tempid = `${areaCode.agreement}_add`;
			}
			table.setAllTableData(tempid, data.agreementVOs[areaCode.agreement]);
		});
	}
	componentWillReceiveProps(nextProp) {
		if (nextProp.showMode === 'card-edit') {
			this.props.form.setFormStatus(this.props.areaCode.card, 'edit');
		}
		if (nextProp.showMode === 'card-browse') {
			this.props.form.setFormStatus(this.props.areaCode.card, 'browse');
		}
	}
	resetState() {
		this.setState({
			showAgreement: false,
			effectParam: null,
			justFrom: null,
			stepData: null
		});
	}
	/* 弹窗模式的下一步方法, 亦用于外部模块调用 */
	nextHandle(sltdt) {
		const { URLS, areaCode, pagecode, form, pkOrg, appcode, meta } = this.props;
		ajax({
			url: URLS.addModal,
			data: {
				pk_psnjobs: sltdt.map((item) => item.data.values.pk_psnjob.value),
				appCode: appcode,
				pageCode: pagecode,
				areaCode: 'dataCard',
				pk_org: pkOrg
			},
			success: (res) => {
				let tempCardid = 'dataCard_add',
					tempAgreementid = 'showAgreement_add';
				let allMeta = meta.getMeta();
				allMeta[tempCardid] = res.data.template[tempCardid];
				allMeta[tempAgreementid] = res.data.template[tempAgreementid];
				// meta.addMeta(allMeta);
				meta.setMeta(allMeta, () => {
					form.setAllFormValue({
						[tempCardid]: { rows: res.data.resultData[tempCardid].rows }
					});
					chectFormAction('', tempCardid, this.props, [ tempCardid ], appcode);
				});
			}
		});
	}
	done(params) {
		const {
			URLS,
			updateState,
			table,
			areaCode,
			form,
			pkOrg,
			json,
			from,
			closeModel,
			appcode,
			meta,
			jumpToNode
		} = this.props;
		const { stepData } = this.state;
		let _params_ = params || {
			step: '0',
			pk_org: pkOrg,
			modename: 'hi_psndoc_ctrt',
			extendtype: null,
			isSelected: false,
			selectedVcontractnums: '',
			appCode: appcode,
			formData: {
				model: form.getAllFormValue('dataCard_add')
			}
		};
		if (!form.isCheckNow('dataCard_add')) {
			return;
		}
		saveValidate(this.props, 'dataCard_add', 'dataCard_add', null, 'form').then(() => {
			let _url_ = URLS.addSave;
			if (stepData) {
				if (parseInt(stepData.step) > 2) {
					_url_ = URLS.addSave2;
				}
				_params_.step = stepData.step;
			}
			ajax({
				url: _url_,
				data: _params_,
				success: (res) => {
					if (res.data) {
						this.setState(
							{
								stepData: res.data
							},
							() => {
								let _stepData_ = this.state.stepData;
								if (res.data && res.data.step !== '99') {
									if (res.data.step === '3') {
										this.done({
											step: _stepData_.step,
											pk_org: _params_.pk_org,
											appCode: appcode,
											isSelected: false,
											savedData: _stepData_.savedData,
											selectedVcontractnums: []
										});
									} else {
										promptBox({
											color: 'warning',
											title: json['cm6011-000030'] /* 国际化处理 '提示' */,
											content: res.data.msg,
											beSureBtnClick: () => {
												if (res.data.step === '5') {
													let metas = this.props.meta.getMeta();
													this.setState(
														{
															showAgreement: true,
															justFrom: 'add'
														},
														() => {
															let allMetas = meta.getMeta();
															let tempid = areaCode.agreement;
															if (`${areaCode.agreement}_add` in allMetas) {
																tempid = `${areaCode.agreement}_add`;
															}
															table.setAllTableData(
																tempid,
																res.data.agreementVOs[areaCode.agreement]
															);
														}
													);
												} else {
													this.done(_params_);
												}
											},
											cancelBtnClick: () => {
												if (parseInt(res.data.step) > 4) {
													this.resetState();
													updateState(
														{
															showMode: 'list-browse',
															showAddModal: false
														},
														function() {
															this.refs.maintable.getTableData();
														}
													);
												} else {
													if (!jumpToNode) {
														this.resetState();
														updateState(
															{
																showMode: 'list-browse',
																showAddModal: false
															},
															function() {
																this.refs.maintable.getTableData();
															}
														);
													} else {
														if (res.data.savedData) { // 已经有解除的单据但是没有生效
															let pk_psndoc_subs = res.data.savedData,
															node_name = appcode === '60110309' ? 'terminate' : 'end';
															jumpToNode(pk_psndoc_subs, node_name);
														} else {
															closeModel();
														}
													}
												}
											}
										});
									}
								} else {
									if (!closeModel) {
										this.resetState();
										updateState(
											{
												showMode: 'list-browse',
												showAddModal: false
											},
											function() {
												this.refs.maintable.getTableData();
											}
										);
									} else {
										closeModel();
									}
								}
							}
						);
					}
				}
			});
		})
	}
	openAgreementModal() {
		const self = this;
		const { showAgreement } = self.state,
			{ table, areaCode, json, meta, updateState } = self.props;
		let allMetas = meta.getMeta();
		let tempid = areaCode.agreement;
		if (`${areaCode.agreement}_add` in allMetas) {
			tempid = `${areaCode.agreement}_add`;
		}

		return (
			<NCModal
				show={showAgreement}
				backdropClosable={false}
				onHide={() => {
					self.setState({ showAgreement: false });
				}}
			>
				<NCModal.Header>
					<NCModal.Title>
						{json['cm6011-000104']}
						{/* 国际化 查看协议 */}
					</NCModal.Title>
				</NCModal.Header>
				<NCModal.Body>
					{table.createSimpleTable(tempid, {
						cancelCustomRightMenu: true,
						showCheck: true,
						showIndex: true
					})}
				</NCModal.Body>
				<NCModal.Footer>
					<NCButton
						onClick={() => {
							self.terminateAgreement();
						}}
						colors="primary"
					>
						{json['cm6011-000028']}
						{/* 国际化 确定 */}
					</NCButton>
					<NCButton
						onClick={() => {
							self.resetState();
							updateState({
								showAddModal: false
							});
						}}
					>
						{json['cm6011-000054']}
						{/* 国际化 取消 */}
					</NCButton>
				</NCModal.Footer>
			</NCModal>
		);
	}
	/* 解除协议 */
	terminateAgreement() {
		const { table, areaCode, form, pkOrg, json, appcode, meta } = this.props;
		const { stepData, justFrom, effectParam } = this.state;
		let allMetas = meta.getMeta();
		let tempid = areaCode.agreement;
		if (`${areaCode.agreement}_add` in allMetas) {
			tempid = `${areaCode.agreement}_add`;
		}
		let sltData = table.getCheckedRows(tempid);
		if (justFrom === 'add') {
			if (sltData.length) {
				this.done({
					step: stepData.step,
					pk_org: pkOrg,
					isSelected: false, // 这是签订协议时的参数
					appCode: appcode,
					savedData: stepData.savedData,
					selectedVcontractnums: sltData.map((item) => item.data.values.vcontractnum.value)
				});
			} else {
				toast({ color: 'danger', content: json['cm6011-000010'] /* 国际化 请选择要操作的条目! */ });
			}
		} else if (justFrom === 'edit') {
			if (sltData.length) {
				this.save({
					baseParam: {
						step: stepData.step,
						areaCode: areaCode.agreement
					},
					formData: {
						model: form.getAllFormValue(areaCode.card)
					},
					selectedVcontractnums: sltData.map((item) => item.data.values.vcontractnum.value)
				});
			} else {
				toast({ color: 'danger', content: json['cm6011-000010'] /* 国际化 请选择要操作的条目! */ });
			}
		} else {
			if (sltData.length) {
				effectParam.selectedVcontractnums = sltData.map((item) => item.data.values.vcontractnum.value);
				this.props.tackEffect(effectParam);
			} else {
				toast({ color: 'danger', content: json['cm6011-000010'] /* 国际化 请选择要操作的条目! */ });
			}
		}
	}
	/* 卡片模式编辑保存 */
	save(params) {
		const self = this;
		const { URLS, updateState, cardPagination, cardViewId, table, areaCode, form, json, pageid} = self.props;
		const { stepData } = this.state;
		if (!form.isCheckNow(areaCode.card)) {
			return;
		}
		saveValidate(this.props, pageid, areaCode.card, null, 'form').then(() => {
			let _formData_ = form.getAllFormValue(areaCode.card);
			_formData_.rows.forEach((item) => {
				if (item.values.numberindex) {
					let numberindex = item.values.numberindex;
					Object.assign(item.values.numberindex, {
						value: String(numberindex.value)
					});
				}
			});
			const _params_ = params || {
				baseParam: {
					step: (stepData && stepData.step) || '0',
					areaCode: areaCode.agreement
				},
				formData: {
					model: _formData_
				},
				selectedVcontractnums: []
			};
			ajax({
				url: URLS.editSave,
				data: JSON.stringify(_params_),
				success: (res) => {
					this.setState({
						stepData: res.data
					});
					if (res.data && res.data.step !== '99') {
						promptBox({
							color: 'warning',
							title: json['cm6011-000030'] /* 国际化处理： 提示*/,
							content: res.data.msg,
							beSureBtnClick: () => {
								if (res.data.step === '4') {
									this.setState(
										{
											showAgreement: true,
											justFrom: 'edit'
										},
										() => {
											this.openAgreementModal();
											table.setAllTableData(
												areaCode.agreement,
												res.data.agreementVOs[areaCode.agreement]
											);
										}
									);
								} else {
									this.save();
								}
							},
							cancelBtnClick: () => {
								this.resetState();
								updateState(
									{
										showMode: 'card-browse'
									},
									() => {
										this.refreshCard();
										cardPagination.setCardPaginationId({ id: cardViewId, status: 1 });
									}
								);
							}
						});
					} else {
						self.resetState();
						updateState(
							{
								showMode: 'list-browse'
							},
							function() {
								this.refs.maintable.getTableData();
							}
						);
					}
				}
			});
		})
	}

	/* form赋值,列表页&卡片页切换时 */
	getFormData(value, record, index = 0) {
		const { areaCode, cardViewId, form, cardPagination, appcode } = this.props;
		form.setAllFormValue({ [areaCode.card]: { rows: [ record ] } });
		chectFormAction('', areaCode.card, this.props, [ areaCode.card ], appcode);
		cardPagination.setCardPaginationId({ id: cardViewId, status: 1 });
	}
	/* 修改保存后刷新卡片数据 */
	refreshCard(value, record, index = 0) {
		const { areaCode, URLS, pkOrg, pagecode, cardViewId, form, cardPagination } = this.props;
		let data = {
			pk_psndoc_sub: cardViewId,
			areaCode: areaCode.card,
			pk_org: pkOrg,
			pageCode: pagecode
		};
		ajax({
			url: URLS.getFormMate,
			data,
			success: (res) => {
				form.setAllFormValue({ [areaCode.card]: { rows: res.data.data[areaCode.card].rows } });
			}
		});
	}
	afterEvent(props, moduleId, key, value, oldValue) {
		let { appcode } = this.props;
		if (key === 'presenter') {
			chectFormAction(key, moduleId, props, [ moduleId ], appcode);
		}
		return value;
	}
	render() {
		const { form, showMode, areaCode } = this.props;
		return (
			<div className="ncc-form">
				{(showMode === 'card-browse' || showMode === 'card-edit') &&
					form.createForm(areaCode.card, {
						onAfterEvent: this.afterEvent.bind(this)
					})}
				{this.state.showAgreement && this.openAgreementModal()}
			</div>
		);
	}
}

export default MainCard;
